<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="$t('videoManager.uploadVideo')"
    :close-on-click-modal="false"
    top="200px"
    width="770px"
    class="component-upload-video"
    @close="handleDialogClose"
  >
    <div class="elx-imgbox-dialog">
      <div class="elx-main">
        <!-- native modifier has been removed, please confirm whether the function has been affected  -->
        <el-form
          label-width="auto"
          @submit.prevent
        >
          <el-form-item :label="$t('resource.selectGroup')+':'">
            <el-select
              v-model="selectGroup"

              clearable
              :placeholder="$t('tip.select')"
              class="select-group-box-item"
            >
              <el-option
                v-for="item in groupList"
                :key="item.attachFileGroupId"
                :label="item.name"
                :value="item.attachFileGroupId"
              />
            </el-select>
            <div
              class="default-btn text-btn select-group-box-item"
              @click="createGroup"
            >
              {{ $t("resource.newGroup") }}
            </div>
          </el-form-item>
          <el-form-item :label="$t('videoManager.uploadVideo')+':'">
            <div class="upload-video-box">
              <div
                v-for="(item, index) in videoList"
                :key="index"
                class="video-preview"
              >
                <video
                  v-if="item.url"
                  class="upShowVideo"
                  :src="item.url"
                  controls="controls"
                  style="width:175px;height:87.5px;"
                />
                <!-- 显示查看和删除的按钮弹窗 -->
                <div class="avatar-uploader-popup">
                  <el-icon
                    class="el-icon-delete"
                    @click="preDeleteVideo(index)"
                  >
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </div>
            <el-upload
              ref="uploadRef"
              :class="['upload-img-preview',uploadNumberLimit()?'uoloadSty':'disUoloadSty']"
              list-type="picture-card"
              action=""
              :multiple="true"
              accept="video/*"
              :auto-upload="false"
              :show-file-list="false"
              :limit="options.limit"
              :before-upload="beforeUploadVideo"
              :http-request="httpRequest"
              :on-change="onUploadChange"
              :on-progress="onUploadProgress"
              :on-exceed="onUploadExceedTip"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <div class="upload-tip">
              {{ uploadTips() }}
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="handleDialogClose"
        >
          {{ $t("shopFeature.edit.back") }}
        </div>
        <div
          class="primary-btn default-btn"
          @click="onUploadConfirm"
        >
          {{ $t("pictureManager.confirmUpload") }}
        </div>
      </div>
    </template>
    <group-add-or-update
      v-if="groupVisible"
      ref="groupAddOrUpdateRef"
      @get-group-data="getGroupList"
      @page-update-group="pageUpdateGroup"
    />
  </el-dialog>
</template>

<script setup>
import { Debounce } from '@/utils/debounce'
import { ElMessage } from 'element-plus'
import http, { uploadFile } from '@/utils/http.js'
const emit = defineEmits([
  'getVideoListData',
  'getGroupData',
  'uploadClose'
])

const options = reactive({
  multiple: true, // 是否支持选取多个图片
  limit: 9, // 最多可选择图片数量
  maxSize: 20, // 最大尺寸（M）
  callback: null
})

const visible = ref(false)
const show = () => {
  visible.value = true
}

const hide = () => {
  visible.value = false
}

const selectGroup = ref('')

const pageUpdateGroup = () => {
  emit('getGroupData')
}

const groupList = ref([]) // 分组列表
/**
 * 获取分组列表
 */
const getGroupList = () => {
  http({
    url: http.adornUrl('/admin/fileGroup/list'),
    method: 'get',
    params: {
      type: 2 // 1、图片 2、视频 3、文件
    }
  }).then(res => {
    groupList.value = res.data
  })
}

const groupVisible = ref(false)
const groupAddOrUpdateRef = ref(null)
const createGroup = () => {
  groupVisible.value = true
  nextTick(() => {
    groupAddOrUpdateRef.value?.show(2)
  })
}

const videoList = ref([])
let isSubmit = false
const uploadRef = ref(null)
/**
 * 提交上传图片
 */
const onUploadConfirm = Debounce(() => {
  if (!videoList.value.length) {
    message($t('videoManager.tips1'), false)
    return
  }
  isSubmit = true
  uploadRef.value?.submit()
}, 1500)

const onUploadProgress = () => {}

/**
 * 上传视频
 */
const httpRequest = (event) => {
  videoList.value.forEach(item => {
    if (item.uid === event.file.uid) {
      uploadFileVideo(event)
    }
  })
}
let resData = []
const uploadFileVideo = (event) => {
  const file = event.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(async ({ data }) => {
    await uploadFile(data.preSignUrl, event.file).then(() => {
      resData.push({ fileId: data.fileId, attachFileGroupId: selectGroup.value, fileSize: file.size, type: 2 })
    })
    if (resData.length === uploadFileNum) {
      http({
        url: http.adornUrl('/admin/file/uploadSuccess'),
        method: 'put',
        data: resData
      }).then(() => {
        resData = []
        event.onSuccess(data.fileId)
        uploadRef.value?.clearFiles()
        setTimeout(() => {
          isSubmit = false
          videoList.value = []
        })
        if (!selectGroup.value) {
          visible.value = false
          emit('getVideoListData')
          return ElMessage({
            type: 'success',
            message: $t('videoManager.video') + $t('resource.uploadSuccess')
          })
        } else {
          ElMessage({
            type: 'success',
            message: $t('videoManager.video') + $t('resource.uploadSuccess')
          })
          emit('getVideoListData')
          visible.value = false
        }
      }).catch((err) => {
        isSubmit = false
        message($t('videoManager.requestError'), true)
        videoList.value = []
        throw err
      })
    }
  })
}

// 视频预上传
const onUploadChange = (file) => {
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    ElMessage.error($t('videoManager.tips3'))
    uploadRef.value?.uploadFiles?.splice(-1, 1)
    return
  }
  if (['video/mp4', 'video/quicktime', 'video/webm'].indexOf(file.raw.type) === -1) {
    ElMessage.error($t('videoManager.tips2'))
    uploadRef.value?.uploadFiles?.splice(-1, 1)
    return false
  }
  if (isSubmit) {
    uploadRef.value?.uploadFiles?.splice(-1, 1)
    return
  }
  const videoSrc = URL.createObjectURL(file.raw)
  videoList.value.push({ url: videoSrc, uid: file.uid })
}

// 删除预览视频
const preDeleteVideo = (index) => {
  uploadRef.value?.uploadFiles?.splice(index, 1)
  videoList.value.splice(index, 1)
}

/**
 * 上传视频前检查合法性
 * @param file
 * @returns {boolean}
 */
const beforeUploadVideo = (file) => {
  return file.size / 1024 / 1024 < 20
}

let uploadFileNum = 0
const images = [] // 已选图片
const uploadNumberLimit = () => {
  if (!options.multiple) {
    return 1
  }
  return options.limit - images.length - uploadFileNum
}

const uploadTypeTip = () => {
  return $t('videoManager.onlySupported') + ' mp4/mov/webm ' + $t('videoManager.video')
}

const uploadSizeTip = () => {
  return $t('videoManager.notExceed') + '20M'
}

const uploadTips = () => {
  const tips = [uploadTypeTip(), uploadSizeTip()]

  if (!options.multiple) {
    return tips.join('，')
  }

  if (images.length > 0) {
    tips.push($t('videoManager.alreadyExist') + images.length + $t('videoManager.unit'))
  }

  const uploadFileNumPar = videoList.value.length
  if (uploadFileNumPar > 0) {
    tips.push($t('videoManager.soonUpload') + uploadFileNumPar + $t('videoManager.unit'))
  }
  uploadFileNum = uploadFileNumPar
  tips.push($t('videoManager.remainder') + (options.limit - images.length - uploadFileNum) + $t('videoManager.unit') + $t('videoManager.upload'))

  return tips.join(',')
}

/**
 * 选择上传文件超过限制文件个数提示
 */
const onUploadExceedTip = () => {
  message($t('videoManager.maxSelect') + uploadNumberLimit() + $t('videoManager.unit') + $t('videoManager.upload'))
}

const message = (msg, isInfo) => {
  let type = 'error'
  if (isInfo) {
    type = 'info'
  }
  ElMessage({
    message: msg,
    type,
    duration: 1500
  })
}

/**
 * 关闭回调
 */
const handleDialogClose = () => {
  visible.value = false
  videoList.value = []
  emit('uploadClose')
}

onMounted(() => {
  getGroupList()
})

defineExpose({
  show,
  hide
})

</script>

<style lang="scss" scoped>
.component-upload-video {
  .disUoloadSty :deep(.el-upload--picture-card){
    display:none;   /* 上传按钮隐藏 */
  }

  &:deep(.search-bar) {
    padding-bottom: 0;
  }
  .select-group-box-item {
    margin-right: 10px;
  }

  div :deep(.el-tabs__header){
    display: none !important;
  }
  &:deep(.operation-bar) {
    margin: 10px 0;
  }
  .upload-tip {
    width: 100%;
    font-size: 12px;
    color: #999999;
  }
  .upload-video-box {
    .video-preview {
      width: 175px;
      height: 100px;
      display: inline-block;
      text-align: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin-right: 8px;
      margin-top: 20px;
    }
  }
  .avatar-uploader-popup{
    width: 100%;
    background: #f6f6f6;
    height: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-icon-delete {
    cursor: pointer;
  }

}

:deep(.elx-main) {
  .el-upload-list__item,.el-upload--picture-card {
    width: 78px !important;
    height: 78px !important;
    line-height: 88px;
    border-radius: 5px;
  }
}
</style>
